package com.jieshuibao.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.CmsArticle;
import com.jieshuibao.model.db.Discuss;
import com.jieshuibao.model.db.DiscussExample;
import com.jieshuibao.model.db.DiscussUser;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.DiscussExample.Criteria;
import com.jieshuibao.model.domain.AddAdmireResponse;
import com.jieshuibao.model.domain.AllDiscussRequest;
import com.jieshuibao.model.domain.AllDiscussResponse;
import com.jieshuibao.model.domain.ArticleDiscussRequest;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.DiscussEdtiRequest;
import com.jieshuibao.service.AnswerService;
import com.jieshuibao.service.ArticelService;
import com.jieshuibao.service.CmsArticleService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.DiscussService;
import com.jieshuibao.service.DiscussUserService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.SensitivewordFilterService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.DateUtils;
import com.jieshuibao.util.UUIDGenerator;

@Controller
@RequestMapping(value = "/discuss")
public class DiscussController {
	private static final Logger logger = LoggerFactory
			.getLogger("DiscussController.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private RedisService redisService;
	@Resource
	private DiscussService discussService;
	@Resource
	private AnswerService answerService;
	@Resource
	private DiscussUserService discussUserService;
	@Resource
	private CmsArticleService cmsArticleService;
	@Resource
	private ArticelService articelService;
	@Resource
	private CounselorDutyService counselorDutyService;
	@Resource
	private UserService userService;
	
	@Resource
	private SensitivewordFilterService SensitivewordFilterService;

	// 答案提交评论
	@ResponseBody
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public Object editDiscuss(HttpServletRequest request,
			@RequestBody DiscussEdtiRequest discussEditRequest) {
		AddAdmireResponse discussEditResponse = new AddAdmireResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(discussEditRequest));
			
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						//用户是否完善信息，未完善个人信息
						boolean completeUser = userService.isCompleteUser(phoneNum);
						if (!completeUser) {
							discussEditResponse.setCode(BaseRes.ERRORPARAM_CODE);
							discussEditResponse.setDes("请完善用户信息");
							return discussEditResponse;
						}
						String answerUuid = discussEditRequest.getAnswerUuid();
						String discussContent = discussEditRequest
								.getDiscussContent();
						
						if (answerUuid != null && discussContent != null) {
							//替换敏感字符
							discussContent = SensitivewordFilterService.replaceSensitiveWord(discussContent, 2, "*");
							Answer answer = answerService
									.getAnswerByUuid(answerUuid);
							if (answer != null) {
								Discuss discuss = new Discuss();
								Answer answer2 = new Answer();
								String uuid = UUIDGenerator.getUUID();
								discuss.setAnswerUuid(answerUuid);
								discuss.setContent(discussContent);
								Date date = new Date();
								if(date.before(DateUtils.getStartTime())||date.after(DateUtils.getEndTime())){
									discuss.setDelFalg("1");
								}else {
									discuss.setDelFalg("0");
								}
								discuss.setDate(date);
								discuss.setUserUuid(phoneNum);
								discuss.setUuid(uuid);
								discuss.setType("2");
								Integer discussNum = answer.getDiscussNum();
								answer2.setUuid(answerUuid);
								answer2.setDiscussNum(discussNum + 1);
								answerService.updateAnswer(answer2);
								discussService.addDiscuss(discuss);
								discussEditResponse.setCode("1");
								discussEditResponse.setDes("亲 评论成功！");
							} else {
								// 数据格式错误
								discussEditResponse.setCode("3");
								discussEditResponse.setDes("数据格式错误");
							}

						} else {
							// 数据格式错误
							discussEditResponse.setCode("3");
							discussEditResponse.setDes("数据格式错误");
						}
					} else {
						// 重新登录
						discussEditResponse.setCode("2");
						discussEditResponse.setDes("请重新登录");
					}
				} else {
					// 重新登录
					discussEditResponse.setCode("2");
					discussEditResponse.setDes("请重新登录");
				}

			
			logger.info("返回：" + mapper.writeValueAsString(discussEditResponse));

		} catch (Exception e) {
			e.printStackTrace();
			discussEditResponse.setCode("0");
			discussEditResponse.setDes("系统繁忙");
		}

		return discussEditResponse;
	}

	// 评论列表接口
	@ResponseBody
	@RequestMapping(value = "/all", method = RequestMethod.POST)
	public Object allDiscuss(HttpServletRequest request,
			@RequestBody AllDiscussRequest allDisCussRequest) {
		AllDiscussResponse allDiscussResponse = new AllDiscussResponse();

		try {
			logger.info("接收：" + mapper.writeValueAsString(allDisCussRequest));
			
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						String answerUuid = allDisCussRequest.getAnswerUuid();
						int maxId = allDisCussRequest.getMaxId();
						int sinceId = allDisCussRequest.getSinceId();
						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}

						if (answerUuid != null) {
							Answer answer = answerService
									.getAnswerByUuid(answerUuid);
							if (answer != null) {
								String uuid = answer.getUuid();
								DiscussExample discussExample = new DiscussExample();
								discussExample.setPageIndex(sinceId - 1);
								discussExample.setPageSize(maxId - sinceId + 1);
								discussExample.setOrderByClause("date desc");
								Criteria criteria = discussExample
										.createCriteria();
								criteria.andAnswerUuidEqualTo(uuid);
								criteria.andDelFalgEqualTo("0");
								List<DiscussUser> discussUsers = discussUserService
										.getDiscussUsers(discussExample);
								
								for (DiscussUser discussUser : discussUsers) {
									String counselorDuty = discussUser.getCounselorDuty();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										StringBuilder stringBuilder=new StringBuilder();
										String[] dutys = counselorDuty.split(",");
										if(dutys!=null){
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														stringBuilder.append(duty.getDutyName()+" ");
													}
												}
												
											}
											int i = stringBuilder.lastIndexOf(" ");
											stringBuilder.delete(i, i+1);
											discussUser.setCounselorDuty(stringBuilder.toString());
										}
										
									}
								}
								allDiscussResponse.setCode("1");
								allDiscussResponse
										.setDiscussUsers(discussUsers);
								allDiscussResponse.setMaxId(sinceId
										+ discussUsers.size() - 1);
								allDiscussResponse.setSinceId(sinceId);
								allDiscussResponse.setRows(discussUsers.size());

							} else {
								// 数据格式错误
								allDiscussResponse.setCode("3");
								allDiscussResponse.setDes("数据格式错误");
							}

						} else {
							// 数据格式错误
							allDiscussResponse.setCode("3");
							allDiscussResponse.setDes("数据格式错误");
						}
					} else {
						// 重新登录
						allDiscussResponse.setCode("2");
						allDiscussResponse.setDes("请重新登录");
					}
				} else {
					// 重新登录
					allDiscussResponse.setCode("2");
					allDiscussResponse.setDes("请重新登录");
				}

			logger.info("返回：" + mapper.writeValueAsString(allDiscussResponse));

		} catch (Exception e) {
			e.printStackTrace();
			allDiscussResponse.setCode("0");
			allDiscussResponse.setDes("系统繁忙");
		}

		return allDiscussResponse;
	}

	// 文章评论列表
	@RequestMapping(value = "/articleDiscuss", method = RequestMethod.POST)
	@ResponseBody
	public Object articleDiscuss(HttpServletRequest request,
			@RequestBody ArticleDiscussRequest articleDiscussRequest) {
		AllDiscussResponse articleDiscussResponse = new AllDiscussResponse();
		try {
			logger.info("接收："
					+ mapper.writeValueAsString(articleDiscussRequest));

						String articleUuid = articleDiscussRequest
								.getArticleUuid();
						if (articleUuid != null && !articleUuid.equals("")) {
							int maxId = articleDiscussRequest.getMaxId();
							int sinceId = articleDiscussRequest.getSinceId();
							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							CmsArticle cmsArticle = cmsArticleService
									.getCmsArticleById(articleUuid);
							if (cmsArticle != null) {
								DiscussExample discussExample = new DiscussExample();
								discussExample.setPageIndex(sinceId - 1);
								discussExample.setPageSize(maxId - sinceId + 1);
								discussExample.setOrderByClause("date desc");
								Criteria criteria = discussExample
										.createCriteria();
								criteria.andAnswerUuidEqualTo(articleUuid);
								criteria.andDelFalgEqualTo("0");
								List<DiscussUser> discussUsers = discussUserService
										.getDiscussUsers(discussExample);
								for (DiscussUser discussUser : discussUsers) {
									String counselorDuty = discussUser.getCounselorDuty();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										StringBuilder stringBuilder=new StringBuilder();
										String[] dutys = counselorDuty.split(",");
										if(dutys!=null){
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														stringBuilder.append(duty.getDutyName()+" ");
													}
													
												}
												
											}
											int i = stringBuilder.lastIndexOf(" ");
											stringBuilder.delete(i, i+1);
											discussUser.setCounselorDuty(stringBuilder.toString());
										}
										
									}
								}
								articleDiscussResponse.setCode("1");
								articleDiscussResponse
										.setDiscussUsers(discussUsers);
								articleDiscussResponse.setMaxId(sinceId
										+ discussUsers.size() - 1);
								articleDiscussResponse.setSinceId(sinceId);
								articleDiscussResponse.setRows(discussUsers
										.size());

							} else {
								// 数据格式错误
								articleDiscussResponse.setCode("3");
								articleDiscussResponse.setDes("数据格式错误");
							}

						} else {
							// 数据格式错误
							articleDiscussResponse.setCode("3");
							articleDiscussResponse.setDes("数据格式错误");
						}

			logger.info("返回："
					+ mapper.writeValueAsString(articleDiscussResponse));

		} catch (Exception e) {

			e.printStackTrace();
			articleDiscussResponse.setCode("0");
			articleDiscussResponse.setDes("系统繁忙");
		}
		return articleDiscussResponse;
	}
		//文章评论提交接口
	@ResponseBody
	@RequestMapping(value = "/editDiscuss", method = RequestMethod.POST)
	public Object editArticleDiscuss(HttpServletRequest request,
			@RequestBody DiscussEdtiRequest discussEditRequest) {
		AddAdmireResponse discussEditResponse = new AddAdmireResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(discussEditRequest));
			
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						//用户是否完善信息，未完善个人信息
						boolean completeUser = userService.isCompleteUser(phoneNum);
						if (!completeUser) {
							discussEditResponse.setCode(BaseRes.ERRORPARAM_CODE);
							discussEditResponse.setDes("请完善用户信息");
							return discussEditResponse;
						}
						String articleUuid = discussEditRequest.getArticleUuid();
						
						String discussContent = discussEditRequest
								.getDiscussContent();
						if (articleUuid != null && discussContent != null&&!articleUuid.equals("")&&!discussContent.equals("")) {
							discussContent = SensitivewordFilterService.replaceSensitiveWord(discussContent, 2, "*");
							CmsArticle article = cmsArticleService.getCmsArticleById(articleUuid);
							if (article != null) {
								Discuss discuss = new Discuss();
								CmsArticle cmsArticle = new CmsArticle();
								String uuid = UUIDGenerator.getUUID();
								discuss.setAnswerUuid(articleUuid);
								discuss.setContent(discussContent);
								Date date = new Date();
								
								if(date.before(DateUtils.getStartTime())||date.after(DateUtils.getEndTime())){
									discuss.setDelFalg("1");
								}else {
									discuss.setDelFalg("0");
								}
								discuss.setDate(date);
								discuss.setUserUuid(phoneNum);
								discuss.setUuid(uuid);
								discuss.setType("1");
								Integer discussNum = article.getDiscussNum();
								cmsArticle.setId(articleUuid);
								cmsArticle.setDiscussNum(discussNum+1);
								articelService.addDiscussAndUpdateArticle(discuss, cmsArticle);
								discussEditResponse.setCode("1");
								discussEditResponse.setDes("亲 评论成功！");
							} else {
								// 数据格式错误
								discussEditResponse.setCode("3");
								discussEditResponse.setDes("数据格式错误");
							}

						} else {
							// 数据格式错误
							discussEditResponse.setCode("3");
							discussEditResponse.setDes("数据格式错误");
						}
					} else {
						// 重新登录
						discussEditResponse.setCode("2");
						discussEditResponse.setDes("请重新登录");
					}
				} else {
					// 重新登录
					discussEditResponse.setCode("2");
					discussEditResponse.setDes("请重新登录");
				}

			logger.info("返回：" + mapper.writeValueAsString(discussEditResponse));

		} catch (Exception e) {
			e.printStackTrace();
			discussEditResponse.setCode("0");
			discussEditResponse.setDes("系统繁忙");
		}

		return discussEditResponse;
	}
}
